package com.lexandro.lemuplayerbot.webdriver;

import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.lexandro.lemuplayerbot.ui.PlayerUI;

@Component("adminUI")
public class WebDriverPlayerUI implements PlayerUI {
	
	private static final String REFRESH_SESSION_FAILED = "Nem sikerult a sessiont frissiteni";

	private static final String LOGIN_PAGE_OPENING_ERROR = "Nem sikerult megnyitni a login oldalt!";

	private static final String LOGIN_ERROR = "Nem sikerult bejelentkezni a jatekba!";

	private static final Logger LOGGER = Logger.getLogger(WebDriverPlayerUI.class);

	@Autowired
	@Qualifier("webDriver")
	private WebDriver webDriver;

	@Override
	public void login(String userName, String password) {
		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("logging in with: " + userName + "/" + password);
		}

		webDriver.get(LOGIN_PAGE_URL);

		checkLoginPageOpened();

		sendKeysToElement(LOGIN_USER_NAME_FIELD_NAME, userName);
		sendKeysToElement(LOGIN_PASSWORD_FIELD_NAME, password);

		submitToElement(LOGIN_PASSWORD_FIELD_NAME);

		checkLoggedIn();
	}

	private void checkLoggedIn() {
		if (!LOGGED_IN_PAGE_TITLE.equals(webDriver.getTitle())) {
			LOGGER.error(LOGIN_ERROR);
			System.out.println(webDriver.getTitle());
			throw new RuntimeException(LOGIN_ERROR);
		}
	}

	public void refreshSession() {
		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("refreshing session");
		}

		webDriver.get(STATISTICS_PAGE_URL);
		System.out.println(webDriver.getTitle());

		if (!STATISTICS_PAGE_TITLE.equals(webDriver.getTitle())) {
			LOGGER.error(REFRESH_SESSION_FAILED);
			throw new RuntimeException(REFRESH_SESSION_FAILED);
		}

	}

	private void checkLoginPageOpened() {
		if (!LOGIN_PAGE_TITLE.equals(webDriver.getTitle())) {
			LOGGER.error(LOGIN_PAGE_OPENING_ERROR);
			throw new RuntimeException(LOGIN_PAGE_OPENING_ERROR);
		}
	}

	private void sendKeysToElement(String elementName, String value) {
		WebElement element = webDriver.findElement(By.name(elementName));
		element.sendKeys(value);
	}

	private void submitToElement(String elementName) {
		WebElement element = webDriver.findElement(By.name(elementName));
		element.submit();
	}

}
